﻿using AwesomeChromeFormUI.App;
using AwesomeChromeFormUI.Cache;
using AwesomeChromeFormUI.CommonExtensions;
using AwesomeChromeFormUI.Configs;
using AwesomeChromeFormUI.Entity;
using AwesomeChromeFormUI.Handlers;
using AwesomeChromeFormUI.Interfaces.Configs;
using AwesomeChromeFormUI.Native;
using AwesomeChromeFormUI.Utils;
using CefSharp;
using CefSharp.WinForms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;

namespace AwesomeChromeFormUI.ChromiumForms
{
    /// <summary>
    /// 主窗口
    /// </summary>
    internal sealed class MainViewImpl : Form, IMainView
    {
        /// <summary>
        /// 主应用
        /// </summary>
        private readonly CefApp _application;
     
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="cefApp"></param>
        public MainViewImpl(CefApp cefApp)
        {
            this._application = cefApp;
            
            InitMainViewConfiguration();

            InitBrowserConfiguration();

            InitMainViewEventHanlders();

            AddChromiumWebBrowser();

            Visible = true;
        }

        /// <summary>
        /// 窗口配置
        /// </summary>
        private void InitMainViewConfiguration()
        {
            MainViewConfiguration configuration = DefaultIMainViewConfiger.CreateCustomMainViewConfiguration();

            // 宽度
            Width = configuration.Width;
            // 高度
            Height = configuration.Height;
            // 标题
            Text = configuration.Text;
            // logo 
            Icon = configuration.Icon;
            // 启动位置
            StartPosition = configuration.StartPosition;
            // 窗口边框
            FormBorderStyle = configuration.FormBorderStyle;
            // 窗口状态
            WindowState = configuration.WindowState;

            if (configuration.FormBorderStyle == FormBorderStyle.None)
            {

                // 启用双缓冲绘制，以减少闪烁
                DoubleBuffered = true;

                // 设置窗口背景颜色
                BackColor = Color.AliceBlue;

                TransparencyKey = BackColor;

                // 设置窗口区域为圆角
                Region = new Region(Drawing2DUtil.GetRoundedRect(new Rectangle(0, 0, Width, Height), 20));

                // 添加窗口阴影
                SetShadow();
            }
        }
        /// <summary>
        /// 重写窗体的OnPaint方法，并在其中绘制具有圆角的窗口边框
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            // 获取窗口的客户区域
            Rectangle rect = new Rectangle(0, 0, this.ClientSize.Width - 1, this.ClientSize.Height - 1);

            // 创建一个圆角路径
            GraphicsPath path = Drawing2DUtil.GetRoundedRect(rect, 20); // 这里的20是圆角的半径

            // 绘制窗口背景
            e.Graphics.FillPath(Brushes.LightGray, path);

            // 绘制窗口边框
            using (Pen pen = new Pen(Color.DarkGray, 2))
            {
                e.Graphics.DrawPath(pen, path);
            }
        }
        
        private const int CS_DROPSHADOW = 0x20000;

        /// <summary>
        /// 重写方法，获取创建控件句柄时所需要的创建参数
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ClassStyle |= CS_DROPSHADOW;
                return cp;
            }
        }

        /// <summary>
        /// 窗口阴影的辅助方法
        /// </summary>
        private void SetShadow()
        {
            // 设置窗口阴影
            var margins = new DwmApiNativeMethods.MARGINS(-1, -1, -1, -1);
            DwmApiNativeMethods.DwmExtendFrameIntoClientArea(this.Handle, ref margins);
        }

        /// <summary>
        /// Browser URL
        /// </summary>
        private string _homeUrl;

        /// <summary>
        /// Browser 配置
        /// </summary>
        private void InitBrowserConfiguration()
        {
            BrowserConfiguration configuration = DefaultIBrowserConfiger.CreateCustomBrowserConfiguration();

            this._homeUrl = configuration.HomeUrl;

            // 创建实例
            this._browser = new ChromiumWebBrowser
            {

                // BrowserSettings
                BrowserSettings = new BrowserSettings()
                {
                    DefaultEncoding = configuration.DefaultEncoding,
                    WebGl = CefState.Enabled
                },

                // 设置宽高与窗口同步
                Height = Height,
                Width = Width
            };

            // 设置右键菜单
            this._browser.SetExtensionMenu();
            // 导出 DotNet 函数
            this._browser.ResolveDotNetObjectThenBoundInJavascript();
            // 处理鼠标信息
            this._browser.SetMouseDownJavascriptMessageReceived();

            // 无边框窗口
            if (FormBorderStyle == FormBorderStyle.None)
            {
                // 自定义标题框
                this._browser.SetDefaultTitleBar();
            }

            // 自定义窗口生命周期
            this._browser.LifeSpanHandler = new DefaultLifeSpanHandler();
        }

        /// <summary>
        /// ChromiumWebBrowser
        /// </summary>
        private ChromiumWebBrowser _browser;

        /// <summary>
        /// Browser 挂载到窗口
        /// </summary>
        private void AddChromiumWebBrowser()
        {
            this.Controls.Add(this._browser);
        }

        /// <summary>
        ///  ChromiumWebBrowser 属性，只能读取
        /// </summary>
        public ChromiumWebBrowser CurrentBrowser 
        { 
            get { return this._browser; } 
        }

        /// <summary>
        /// 初始化窗口事件
        /// </summary>
        private void InitMainViewEventHanlders()
        {
            // 显示窗口前加载 URL 
            Load += (sender, e) =>
            {
                this._browser.Load(this._homeUrl);
                GlobalFormHandleCache.Cache.Add(
                    this.Handle.ToString(),
                    new FormLocationEntity() 
                    { 
                        lastHeight = this.Height,
                        lastWidth = this.Width,
                        lastLocation = this.Location,
                        isMaximized = this.WindowState == FormWindowState.Maximized 
                    });
            };
            // 关闭窗口前释放资源
            FormClosing += (sender, e) =>
            {
                this._browser.Dispose();
                GlobalFormHandleCache.Cache.Remove(this.Handle.ToString());
            };
            // 关闭应用
            FormClosed += (sender, e) =>
            {
                this._application.Quit();
            };
            // 自适应窗口大小
            Resize += (sender, e) =>
            {
                //this._browser.Width = Width;
                this._browser.Width = ClientSize.Width;
                //this._browser.Height = Height;
                this._browser.Height = ClientSize.Height;
            };
        }

    }
}
